<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>购物车</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <table border="1px" width="50%" height="450px" align="center" cellspacing="0">
            <tr bgcolor="#F7F7F7">
                <th></th>
                <th>书籍名称</th>
                <th>出版日期</th>
                <th>价格</th>
                <th>购买数量</th>
                <th>操作</th>
            </tr>
            <tr v-for="(item,index) in items" align="center">
                <td>&nbsp;{{index + 1}}&nbsp;</td>
                <td>{{item.name}}</td>
                <td>{{item.date}}</td>
                <td>￥{{item.price}}</td>
                <td>
                    <button @click="handleReduce(index)" :disabled="item.count ===1">-</button>
                    {{item.count}}
                    <button @click="handleAdd(index)">+</button>
                </td>
                <td>
                    <button @click="handleRemove(index)">移除</button
                ></td>
            </tr>
        </table>
        <p align="center">总价格 : ￥{{totalPrice}}</p>

    </div>

</body>

<script>
    var app = new Vue({
        el: '#app',
        data: {
            items: [
                {
                    name: "<<java编程思想>>",
                    date: "2020-9",
                    price: 98.00,
                    count: 1
                },
                {
                    name: "<<数据分析与数据原理>>",
                    date: "2020-2",
                    price: 39.00,
                    count: 1
                },
                {
                    name: "<<Hadoop权威指南>>",
                    date: "2020-10",
                    price: 59.00,
                    count: 1
                },
                {
                    name: "<<代码大全>>",
                    date: "2020-8",
                    price: 128.00,
                    count: 1
                }
            ]
        },
        methods: {
            //减少商品数量
            handleReduce(index) {
                if (this.items[index].count === 1) return
                this.items[index].count--
            },
            //增加商品数量
            handleAdd(index) {
                this.items[index].count++
            },
            //从购物车中移除该商品
            handleRemove(index) {
                this.items.splice(index,1)
            }
        },
        computed: {
            //计算并获取总价
            totalPrice() {
                let total = 0
                for (let i = 0; i < this.items.length; i++) {
                    let item = this.items[i]
                    total += item.price * item.count
                }
                return total.toString()
            }
        },


    })
</script>

</html>